//
//  ViewController.m
//  19_JSON网易
//
//  Created by 徐昊 on 16/8/9.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "HXTitleCollectionViewLayout.h"
#import "TitleCollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, HXTileCollectionViewLayoutDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray<NewsTitle *> *newsTitleArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.newsTitleArray = [NSMutableArray array];
    [self hanleData];
    HXTitleCollectionViewLayout *layout = (HXTitleCollectionViewLayout *)self.collectionView.collectionViewLayout;
    layout.delegate = self;
}
- (void)hanleData {
    NSString *newsJSON = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    NSData *JSONData = [NSData dataWithContentsOfFile:newsJSON];
    // JSON解析
    NSError *error = nil;
    NSDictionary *newsTitleDic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = newsTitleDic[@"tList"];
    for (NSDictionary *newsTitle in list) {
        NewsTitle *news = [NewsTitle newsTitleWtihDic:newsTitle];
        [_newsTitleArray addObject:news];
    }
    
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout height:(CGFloat)height heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsTitle *title = _newsTitleArray[indexPath.row];
    CGRect newRext = [title.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.collectionView.bounds)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceil(CGRectGetWidth(newRext));
    return width;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _newsTitleArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.tName.text = [_newsTitleArray[indexPath.row] tname];
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
